﻿namespace KinonekoSoftware.Foundation.UI.Commands
{

    public class FuncCommand<T> : ICommandEX
    {
        public FuncCommand(Action<T> executeHandler)
        {
            ExecuteHandler = executeHandler ?? throw new ArgumentNullException(nameof(executeHandler));
        }

        public FuncCommand(Action<T> executeHandler, Predicate<T> canExecuteHandler)
        {
            ExecuteHandler    = executeHandler    ?? throw new ArgumentNullException(nameof(executeHandler));
            CanExecuteHandler = canExecuteHandler ?? throw new ArgumentNullException(nameof(canExecuteHandler));

        }

        public bool CanExecute(object parameter)
        {
            if (CanExecuteHandler is null)
            {
                return true;
            }

            if (parameter is T v)
            {
                
                return CanExecuteHandler(v);
            }

            return false;
        }

        public void Execute(object parameter)
        {

            var v = parameter is T p ? p : default(T);
            ExecuteHandler(v);
        }

        public Action<T>    ExecuteHandler    { get; }
        public Predicate<T> CanExecuteHandler { get; }
        public void RaiseUpdate() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);

        public event EventHandler CanExecuteChanged;
    }
}